﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Spark;
using Spark.FileSystem;
using Spark.Web.Mvc;
using System.IO;

namespace Meraz.Web.Controllers
{
    public abstract class BaseController : Controller
    {
        public string RenderViewToHtml<VIEW_MODEL>(string viewPathAndName, VIEW_MODEL viewModel) where VIEW_MODEL : class
        {
            var templatesLocation = new FileSystemViewFolder(Server.MapPath("~/Views"));
            var viewEngine = new SparkViewEngine(BuildSparkSettings()) { ViewFolder = templatesLocation };
            var descriptor = new SparkViewDescriptor().AddTemplate(viewPathAndName);

            var view = (SparkView<VIEW_MODEL>)viewEngine.CreateInstance(descriptor);
            view.ViewData = new ViewDataDictionary<VIEW_MODEL>(viewModel);

            string html;

            using (var writer = new StringWriter())
            {
                view.RenderView(writer);
                html = writer.ToString();
            }

            return html;
        }
        public static SparkSettings BuildSparkSettings()
        {
            return new SparkSettings()
                .AddNamespace("System")
                .AddNamespace("System.Collections.Generic")
                .AddNamespace("System.Linq")
                .AddNamespace("System.Web.Mvc")
                .AddNamespace("System.Web.Mvc.Html")
                .AddNamespace("Meraz.Web.Views.Helpers")
                .SetPageBaseType(typeof(SparkView))
                .SetDebug(false);
        }

        public ActionResult GetPartialSparkView(string viewPath, string viewDataKey, object model)
        {
            // Set up your spark engine goodness.  
            var settings = new SparkSettings().SetPageBaseType(typeof(SparkView));
            var templates = new FileSystemViewFolder(Server.MapPath("~/Views"));
            var engine = new SparkViewEngine(settings) { ViewFolder = templates };

            // "Describe" the view (the template, it is a template after all), and its details.  
            var descriptor = new SparkViewDescriptor().AddTemplate(viewPath);

            // Create a spark view engine instance
            var view = (SparkView)engine.CreateInstance(descriptor);

            // Add some junk to the view data for the view to use.  
            view.ViewData[viewDataKey] = model;

            // Render the view to a text writer.  
            var writer = new StringWriter(); 
            view.RenderView(writer);

            // Tap keg, throw party.  
            return Content(writer.ToString()); 

        }
    }
}